//
//  NSString+ZHWDES.m
//  24-加密
//
//  Created by dllo on 16/8/16.
//  Copyright © 2016年 ZHW. All rights reserved.
//

#import "NSString+ZHWDES.h"
#import <CommonCrypto/CommonCrypto.h>
// 必须8位
#define key @"01234567"
static Byte iv[] = {1, 2, 3, 4, 5, 6, 7, 8};
@implementation NSString (ZHWDES)
- (NSString *)stringWithDES {
    // 将字符串本身转换成C字符串
    const char *cString = [self UTF8String];
    //
    unsigned char bytes[1024];
    // 容器大小
    size_t dataOutMoved = 0;
    // DES加密过程
    // 参数1: 加密/ 解密 参数2: 加密/解密 方式
    // 参数3:
    // 参数4: 密钥
    // 参数5: 密钥的大小
    // 参数6: 向量
    // 参数7: C字符串
    // 参数8: 长度
    // 参数9: 接收容器
    // 参数10: 容器大小
    // 参数11: 容器最终的个数
    CCCryptorStatus cryptorStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, cString, strlen(cString), bytes, 1024, &dataOutMoved);
    // 判断是否成功
    if (cryptorStatus == kCCSuccess) {
        NSLog(@"成功");
        // 转成字符串
        NSData *desData = [NSData dataWithBytes:bytes length:dataOutMoved];
        NSString *desBase64String = [desData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        return desBase64String;
    } else {
        NSLog(@"加密失败");
        return nil;
    }
}

- (NSString *)desWithString {
    NSData *data = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    const void *byte = data.bytes;
    unsigned char bytes[1024];
    size_t dataOutMoved = 0;
    CCCryptorStatus cryptorStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, byte, [data length], bytes, 1024, &dataOutMoved);
    if (cryptorStatus == kCCSuccess) {
       
        NSData *soureceData = [[NSData alloc] initWithBytes:bytes length:dataOutMoved];
        NSString *sourceString = [[NSString alloc] initWithData:soureceData encoding:NSUTF8StringEncoding];
        return sourceString;
    } else {
        NSLog(@"解码失败"); 
        return nil;
    }
}
@end
